package com.example.elmmerchants.Order_Setting;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.elmmerchants.Auto_Get_Order_Page;
import com.example.elmmerchants.R;
import com.example.elmmerchants.Ringtone_Setting.Ringtone_Setting_Page;
import com.example.elmmerchants.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Order_Setting_Page extends AppCompatActivity {

    RelativeLayout auto_order_setting, ringtone_setting, book_order_setting, how_many_time_finish_order;
    TextView is_open_auto_order_text_view;
    AlertDialog dialog;

    String email, open_time, close_time, open_day, open_time_2 = "", close_time_2 = "";
    boolean is_open_auto_get_order;
    boolean is_loading_auto_get_order_data = false;
    int is_all_day_can_book_order, can_served_start_time, can_served_end_time, served_which_time_remind;
    int book_almost_time, book_has_ride_get_order, new_order, auto_get_order, reminder_order, order_cancel, user_apply_refund, abnormal_distribution, how_many_volume;
    boolean open_book_order, is_finish_loading_book_order_data = false, is_finish_loading_ringtone_data = false;
    boolean is_open_vibrate = false;
    String[] all_min = new String[]{"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59"};

    private class Loading_Ringtone_Data_Thread extends Thread {
        @Override
        public void run() {
            is_finish_loading_ringtone_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant_ringtone_setting WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        book_almost_time = set.getInt("book_almost_time");
                        book_has_ride_get_order = set.getInt("book_has_ride_get_order");
                        new_order = set.getInt("new_order");
                        auto_get_order = set.getInt("auto_order");
                        reminder_order = set.getInt("reminder_order");
                        order_cancel = set.getInt("order_cancel");
                        user_apply_refund = set.getInt("user_apply_refund");
                        abnormal_distribution = set.getInt("abnormal_distribution");
                        how_many_volume = set.getInt("volume");
                        if (set.getInt("is_open_vibrate") == 1) {
                            is_open_vibrate = true;
                        }
                        else {
                            is_open_vibrate = false;
                        }
                        is_finish_loading_ringtone_data = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_finish_loading_ringtone_data) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(Order_Setting_Page.this, Ringtone_Setting_Page.class);
                    intent.putExtra("email", email);
                    intent.putExtra("book_almost_time", book_almost_time);
                    intent.putExtra("book_has_ride_get_order", book_has_ride_get_order);
                    intent.putExtra("new_order", new_order);
                    intent.putExtra("auto_get_order", auto_get_order);
                    intent.putExtra("reminder_order", reminder_order);
                    intent.putExtra("order_cancel", order_cancel);
                    intent.putExtra("user_apply_refund", user_apply_refund);
                    intent.putExtra("abnormal_distribution", abnormal_distribution);
                    intent.putExtra("how_many_volume", how_many_volume);
                    intent.putExtra("is_open_vibrate", is_open_vibrate);
                    startActivityForResult(intent, 2);
                }
            });
        }
    }

    private class Book_Order_Setting_Thread extends Thread {
        @Override
        public void run() {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant_book_order_setting WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        is_all_day_can_book_order = set.getInt("is_all_day_can_book_order");
                        can_served_start_time = set.getInt("can_served_start_time");
                        can_served_end_time = set.getInt("can_served_end_time");
                        served_which_time_remind = set.getInt("served_which_time_remind");
                        if (set.getInt("is_open_book_order") == 1) {
                            open_book_order = true;
                        }
                        else {
                            open_book_order = false;
                        }
                    }

                    String sql2 = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
                    preparedStatement2.setString(1, email);
                    ResultSet set2 = preparedStatement2.executeQuery();
                    while (set2.next()) {
                        open_time = set2.getString("open_hour");
                        close_time = set2.getString("close_hour");
                        open_day = set2.getString("open_day");
                        open_time_2 = set2.getString("open_hour2");
                        close_time_2 = set2.getString("close_hour2");
                        is_finish_loading_book_order_data = true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_finish_loading_book_order_data) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(Order_Setting_Page.this, Book_Order_Setting.class);
                    intent.putExtra("email", email);
                    intent.putExtra("is_all_day_can_book_order", is_all_day_can_book_order);
                    intent.putExtra("can_served_start_time", can_served_start_time);
                    intent.putExtra("served_which_time_remind", served_which_time_remind);
                    intent.putExtra("can_served_end_time", can_served_end_time);
                    intent.putExtra("open_book_order", open_book_order);
                    intent.putExtra("open_time", open_time);
                    intent.putExtra("close_time", close_time);
                    intent.putExtra("open_day", open_day);
                    intent.putExtra("open_time_2", open_time_2);
                    intent.putExtra("close_time_2", close_time_2);
                    startActivityForResult(intent, 3);
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_setting_page);

        email = getIntent().getStringExtra("email");
        is_open_auto_get_order = getIntent().getBooleanExtra("is_open_auto_get_order", false);

        auto_order_setting = findViewById(R.id.auto_order_setting);
        ringtone_setting = findViewById(R.id.ringtone_setting);
        is_open_auto_order_text_view = findViewById(R.id.is_open_auto_order_text_view);
        book_order_setting = findViewById(R.id.book_order_setting);
        how_many_time_finish_order = findViewById(R.id.how_many_time_finish_order);

        if (is_open_auto_get_order) {
            is_open_auto_order_text_view.setText("自动接单中");
        }
        else {
            is_open_auto_order_text_view.setText("手动接单中");
        }

        auto_order_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Order_Setting_Page.this, Auto_Get_Order_Page.class);
                intent.putExtra("email", email);
                intent.putExtra("is_open_auto_get_order", is_open_auto_get_order);
                startActivityForResult(intent, 1);
            }
        });

        ringtone_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_dialog();
                Loading_Ringtone_Data_Thread loadingRingtoneDataThread = new Loading_Ringtone_Data_Thread();
                loadingRingtoneDataThread.start();
            }
        });

        book_order_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_dialog();
                Book_Order_Setting_Thread bookOrderSettingThread = new Book_Order_Setting_Thread();
                bookOrderSettingThread.start();
            }
        });

        how_many_time_finish_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_should_how_many_time_finish_food_dialog();
            }
        });
    }

    void set_should_how_many_time_finish_food_dialog() {
        Dialog dialog1 = new Dialog(this);
        dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog1.setContentView(R.layout.choose_how_many_time_should_finish_food_bottomsheet);
        TextView time_text_view = dialog1.findViewById(R.id.time_text_view);
        time_text_view.setText("0");
        NumberPicker how_many_time = dialog1.findViewById(R.id.how_many_time);
        how_many_time.setMaxValue(all_min.length - 1);
        how_many_time.setDisplayedValues(all_min);
        how_many_time.setMinValue(0);
        how_many_time.setValue(0);
        how_many_time.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int i, int i1) {
                time_text_view.setText(String.valueOf(numberPicker.getValue()));
            }
        });
        Button save = dialog1.findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ExecutorService executorService = Executors.newSingleThreadExecutor();
                executorService.execute(() -> {
                    try {
                        Connection_SQL userSQL = new Connection_SQL();
                        Connection connection = userSQL.connection();
                        String sql = "update `merchant_book_order_setting` set how_many_time_should_finish_food = ? where email = ?";
                        PreparedStatement preparedStatement = connection.prepareStatement(sql);
                        preparedStatement.setInt(1, how_many_time.getValue());
                        preparedStatement.setString(2, email);
                        preparedStatement.executeUpdate();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    runOnUiThread(() -> {
                        try {
                            Thread.sleep(100);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        dialog1.dismiss();
                    });
                });
            }
        });
        Button close_page = dialog1.findViewById(R.id.close_page);
        close_page.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog1.dismiss();
            }
        });

        dialog1.show();
        dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
        dialog1.getWindow().setGravity(Gravity.BOTTOM);
    }

    void book_order_data() {
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater1 = LayoutInflater.from(this);
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1: {
                if (data != null) {
                    if (data.getBooleanExtra("is_open", false)) {
                        is_open_auto_order_text_view.setText("手动接单中");
                        is_open_auto_get_order = false;
                    }
                    else {
                        is_open_auto_order_text_view.setText("自动接单中");
                        is_open_auto_get_order = true;
                    }
                }
                break;
            }
            case 2: {
                //ringtone_data();
                break;
            }
            case 3: {
                //book_order_data();
                break;
            }
        }
    }
}